package com.azt.back.interceptor;

import java.util.List;
import java.util.Properties;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.azt.api.pojo.Admin;
import com.azt.api.service.FuncService;
import com.azt.back.util.ContextUtils;
import com.azt.back.util.Globals;
import com.azt.utils.IpUtil;

public class BackContextInterceptor extends HandlerInterceptorAdapter {

	@Autowired
	private FuncService manager;

//	@Value("#{iplimit}")
//	private Properties ipLimit;

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

		Admin admin = (Admin) request.getSession().getAttribute(Globals.ADMIN_SESSION);
		String requestURI = request.getRequestURI();

		/**
		 * IP限制
		 */
/*		String ip = IpUtil.getIpAddr(request);
		if (!ipLimit.containsValue(ip)) {
			request.getRequestDispatcher("/error/404.html").forward(request, response);
			return false;
		}*/

		/**
		 * 格式化请求路径
		 */
		requestURI = requestURI.replaceAll("/{2,}", "/");
		// 判断是否登录
		if (admin == null && !excludeUrls.contains(requestURI)) {
			response.sendRedirect("/admin/login.do");
			return false;
		}

		// 判断有没有权限,用户不为空，过滤登录相关请求，并且在权限控制范围内
		Boolean pass = true;
		if (admin != null && !excludeUrls.contains(requestURI) && getAllFunction().contains(requestURI)) {
			pass = false;
			List<String> functions = ContextUtils.getFunctions();
			for (String func : functions) {

				if (func != null && !"".equals(func)) {
					if (requestURI.startsWith(func)) {
						pass = true;
						break;
					}
				}
			}
		}
		// 无权限则跳转提示页
		if (!pass) {
			response.sendRedirect("/admin/noperm.do");
		}
		return pass;
	}

	private List<String> getAllFunction() {
		List<String> allPermission = ContextUtils.getAllPermission();
		if (allPermission == null || ContextUtils.has_changed) {
			allPermission = manager.functionpath(null);
			ContextUtils.setAllPermission(allPermission);
			ContextUtils.has_changed = false;
		}
		return allPermission;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView mav) throws Exception {
	}

	private List<String> excludeUrls;

	public List<String> getExcludeUrls() {
		return excludeUrls;
	}

	public void setExcludeUrls(List<String> excludeUrls) {
		this.excludeUrls = excludeUrls;
	}

}